package com.spring.util;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

/**
 * @author 作者 E-mail: liuyang
 * @date 创建时间：2016年9月12日 上午11:05:18
 * @version 2.0
 * @parameter
 * @since
 * @return
 */
public class CsvWriter {

	/** CSV文件列分隔符 */
	private static final String CSV_COLUMN_SEPARATOR = ",";

	/** CSV文件列分隔符 */
	private static final String CSV_RN = "\r\n\t";

	/**
	 * 
	 * 将检索数据输出的对应的csv列中
	 */

	public static String formatCsvData(List<?> data, String displayColNames, String matchColNames) {

		StringBuffer buf = new StringBuffer();

		String[] displayColNamesArr = null;
		String[] matchColNamesMapArr = null;

		displayColNamesArr = displayColNames.split(",");
		matchColNamesMapArr = matchColNames.split(",");

		// 输出列头
		for (int i = 0; i < displayColNamesArr.length; i++) {
			buf.append(displayColNamesArr[i]).append(CSV_COLUMN_SEPARATOR);
		}
		buf.append(CSV_RN);

		if (null != data) {
			// 输出数据
			for (int i = 0; i < data.size(); i++) {

				for (int j = 0; j < matchColNamesMapArr.length; j++) {
					buf.append(method(data.get(i), matchColNamesMapArr[j])).append(CSV_COLUMN_SEPARATOR);
				}
				buf.append(CSV_RN);
			}
		}
		return buf.toString();
	}

	public static Object method(Object obj, String filed) {
		Object o = "";
		try {
			Class clazz = obj.getClass();
			PropertyDescriptor pd = new PropertyDescriptor(filed, clazz);
			if (pd != null) {
			     Method getMethod = pd.getReadMethod();// 获得get方法

				 Type returnType = getMethod.getGenericReturnType();// 返回类型
				 o = getMethod.invoke(obj);// 执行get方法返回一个Object
				
				if (o == null) {
					o = "";
				} else if (returnType.getTypeName().equals("java.util.Date")) {
					o = DateUtils.formatDate((Date) o, DateUtils.DEFAULT_TIME_FORMAT);
				}else if (filed.equals("idCard") || filed.equals("account") || filed.equals("inviteCode") || filed.equals("code")) {
					o =o+"\t";
				}

			}
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IntrospectionException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return o.toString().replace(",","，");
	}

	public static void exportCsv(String fileName, String content, HttpServletResponse response) throws IOException {

		// 设置文件后缀
		String fn = fileName.concat("-" + DateUtils.formatDate(new Date()) + ".csv");

		// 读取字符编码
		String csvEncoding = "GBK";

		// 设置响应
		response.setCharacterEncoding(csvEncoding);
		response.setContentType("text/csv; charset=" + csvEncoding);
		response.setHeader("Pragma", "public");
		response.setHeader("Cache-Control", "max-age=30");
		response.setHeader("Content-Disposition", "attachment; filename=" + fn);

		// 写出响应
		OutputStream os = response.getOutputStream();
		os.write(content.getBytes("GBK"));
		os.flush();
		os.close();
	}

}
